package com.cssl.service.impl;

import cn.dev33.satoken.exception.NotLoginException;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.cssl.domain.DtsCoupon;
import com.cssl.mapper.DtsCouponMapper;
import com.cssl.service.DtsCouponService;
import com.cssl.util.*;
import com.fasterxml.jackson.core.type.TypeReference;
import org.hibernate.mapping.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 优惠券
 */
@Service
public class

DtsCouponServiceImpl implements DtsCouponService {
    @Autowired
    private DtsCouponMapper mapper;
    @Autowired
    private StringRedisTemplate template;
    @Autowired
    private ObjectMapperUtil objectMapperUtil;

    @Override
    public List<DtsCoupon> getAllInfo() {
        //存储进redis(coupon)
        String s = template.opsForValue().get(StorageVariable.COUPON);
        if (StrUtil.isEmpty(s)) {
            //查询数据库
            List<DtsCoupon> allInfo = mapper.getAllInfo();
            template.opsForValue().set(StorageVariable.COUPON, objectMapperUtil.toJsonString(allInfo), 7, TimeUnit.DAYS);
            return allInfo;
        }
        //redis不为空
        List<DtsCoupon> dtsCoupons = objectMapperUtil.fromJsonString(s, new TypeReference<List<DtsCoupon>>() {
        });
        return dtsCoupons;
    }

    @Override
    public Result homePageCoupon() {
        Integer loginIdAsInt;
        try {
            loginIdAsInt = StpKit.USER.getLoginIdAsInt();
        } catch (NotLoginException e) {
            System.out.println("用户未登录" + e);
            loginIdAsInt = -1;
        }
        List<DtsCoupon> dtsCoupons = mapper.homePageCoupon(loginIdAsInt);
        if (dtsCoupons.isEmpty()) {
            return Result.fail(InfoCode.QUERY_EMPTY, InfoCode.MESSAGE_QUERY_EMPTY, System.currentTimeMillis());
        }
        return Result.result(InfoCode.OK, InfoCode.MESSAGE_OK, dtsCoupons, System.currentTimeMillis());
    }

    @Override
    public Result getUserCoupOn() {
        Integer login = 0;
        try {
            login = StpKit.USER.getLoginIdAsInt();
        } catch (NotLoginException e) {
            System.out.println("e = " + e);
        }
        if (ObjUtil.isEmpty(login) || login == 0) {
            return Result.fail(InfoCode.UNLOGIN, InfoCode.MESSAGE_UNLOGIN, System.currentTimeMillis());
        }
        List<Map> couponList = mapper.getUserCoupon(login);
        return Result.result(InfoCode.OK,InfoCode.MESSAGE_OK,couponList,System.currentTimeMillis());
    }
}
